package cn.iocoder.yudao.module.member.point.api;

import cn.iocoder.yudao.module.api.member.point.MemberPointApi;
import cn.iocoder.yudao.module.api.member.point.enums.MemberPointBizTypeEnum;
import cn.iocoder.yudao.module.member.assets.dal.dataobject.MemberDigitalAssetsDO;
import cn.iocoder.yudao.module.member.assets.service.AppMemberDigitalAssetsService;
import cn.iocoder.yudao.module.member.point.service.MemberPointRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.api.member.ErrorCodeConstants.POINT_RECORD_BIZ_NOT_SUPPORT;

/**
 * 用户积分的 API 实现类
 *
 * @author owen
 */
@Slf4j
@Service
@Validated
public class MemberPointApiImpl implements MemberPointApi {

    @Resource
    private MemberPointRecordService memberPointRecordService;
    @Resource
    private AppMemberDigitalAssetsService memberDigitalAssetsService;

    @Override
    public void addPoint(Long userId, Integer point, Integer bizType, String bizId) {
        if (point == null || point <= 0) {
            log.warn("[addPoint][userId({}) point({}) bizType({}) bizId({}) 无法增加积分，因为积分为空或者小于等于 0]",
                    userId, point, bizType, bizId);
            return;
        }
        MemberPointBizTypeEnum bizTypeEnum = MemberPointBizTypeEnum.getByType(bizType);
        if (bizTypeEnum == null) {
            throw exception(POINT_RECORD_BIZ_NOT_SUPPORT);
        }
        memberPointRecordService.createPointRecord(userId, point, bizTypeEnum, bizId);
    }

    @Override
    public void reducePoint(Long userId, Integer point, Integer bizType, String bizId) {
        if (point == null || point <= 0) {
            log.warn("[reducePoint][userId({}) point({}) bizType({}) bizId({}) 无法减少积分，因为积分为空或者小于等于 0]",
                    userId, point, bizType, bizId);
            return;
        }
        MemberPointBizTypeEnum bizTypeEnum = MemberPointBizTypeEnum.getByType(bizType);
        if (bizTypeEnum == null) {
            throw exception(POINT_RECORD_BIZ_NOT_SUPPORT);
        }
        memberPointRecordService.createPointRecord(userId, -1 * point, bizTypeEnum, bizId);
    }

    @Override
    public Integer getPointByUserId(Long userId) {
        MemberDigitalAssetsDO digitalAssets = memberDigitalAssetsService.getOrCreate(userId);
        if (digitalAssets == null) {
            return 0;
        }
        return digitalAssets.getPoint();
    }

}
